package org.zoomdev.zoom.web.utils;

import com.alibaba.fastjson2.JSONWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zoomdev.zoom.common.io.Io;
import org.zoomdev.zoom.common.json.JSON;
import org.zoomdev.zoom.common.utils.Classes;
import org.zoomdev.zoom.web.modules.CoreWebModule;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Writer;


public class ResponseUtils {

    private static final Logger log = LoggerFactory.getLogger(CoreWebModule.class);

    /**
     * 使用write输出
     *
     * @param response
     * @param content
     */
    public static void writeString(HttpServletResponse response, String content) {
        Writer writer = null;
        try {
            response.setContentType("text/html;charset=utf-8");
            writer = response.getWriter();
            writer.write(content);
        } catch (Throwable e) {
            log.error("HttpServletResponse输出发生异常", Classes.getCause(e));
        } finally {
            Io.close(writer);
        }

    }


    public static void writeJson(HttpServletResponse response, Object data) {
        writeJson(response, data, false);
    }

    public static void writeJson(HttpServletResponse response, Object data, boolean pretty) {
        response.setContentType("application/json; charset=utf-8");
        try (OutputStream os = response.getOutputStream()) {
            if (pretty) {
                com.alibaba.fastjson2.JSON.writeTo(os, data, JSONWriter.Feature.PrettyFormat);
            } else {
                JSON.write(os, data);
            }
        } catch (IOException e) {
            log.error("HttpServletResponse输出发生异常", Classes.getCause(e));
        }
    }

    public static void writeBytes(HttpServletResponse response, byte[] bytes) {
        OutputStream writer = null;
        try {
            response.addHeader("Content-Length", String.valueOf(bytes.length));
            writer = response.getOutputStream();
            writer.write(bytes);
        } catch (Throwable e) {
            log.error("HttpServletResponse输出发生异常", Classes.getCause(e));
        } finally {
            Io.close(writer);
        }
    }

    public static void writeInputStream(HttpServletResponse response, InputStream inputStream, int length) {

        OutputStream writer = null;
        try {

            writer = response.getOutputStream();
            byte[] buffer = new byte[4096];
            int total = 0;
            while (total < length) {
                int readed = Io.read(inputStream, buffer);
                if (readed <= 0) {
                    break;
                }
                total += readed;
                writer.write(buffer, 0, readed);
            }
        } catch (Throwable e) {
            log.error("HttpServletResponse输出发生异常", Classes.getCause(e));
        } finally {
            Io.close(writer);
        }
    }


}
